﻿/**************************************************
 * 
 *      创建：lito
 * 
 *      时间：2016-01-27
 *      
 *      描述：用户系统全局性方法调用
 * 
 * ************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NF_Mode;
using System.Drawing;
using System.IO;
using System.Collections;
using System.Net;
using Microsoft.Win32;
using System.Security.Cryptography;

namespace NF_Base
{
    public class BaseClass
    {
        #region - 宏 -

        /// <summary>
        /// 数据库连接地址
        /// </summary>
        public static string ServerConnection = string.Empty;         //服务器地址

        /// <summary>
        /// 当前登陆用户
        /// </summary>
        public static SysUser us = new SysUser();

        /// <summary>
        /// 当前登陆用户角色
        /// </summary>
        public static SysRole ro = new SysRole();

        //public static Form MinxFrm = null;                  //当前最小化的窗体
        public static string Filter = "图像文件(*.BMP;*.JPG;*.GIF;*.PNG;*.JPEG)|*.BMP;*.JPG;*.GIF;*.PNG;*.JPEG|所有文件(*.*)|*.*";
        public static string ConnectPrinter = string.Empty; //设置是否连接打印机
        public static string IsDown = string.Empty;         //是否启用结账并下做



        #endregion




        /// <summary>
        /// 打开窗体
        /// </summary>
        /// <param name="frm">窗体</param>
        public static void OpenWindow(Form frm, Panel ct)
        {
            if (frm == null) return;
            if (ct.Controls.Count > 0)
            {
                Form oldfrm = ct.Controls[0] as Form;
                oldfrm.Close();
            }

            frm.TopLevel = false;
            frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            frm.Dock = DockStyle.Fill;
            frm.Show();
            ct.Controls.Add(frm);
        }


        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">时间戳</param>
        /// <returns>时间</returns>
        public static DateTime StampToDateTime(string timeStamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dateTimeStart.Add(toNow);
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>时间戳</returns>
        public static int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 解析图片
        /// </summary>
        /// <param name="imagefile">图片</param>
        /// <returns>流</returns>
        public static string GetBase64FromImage(string imagefile)
        {
            string strbaser64 = "";
            try
            {
                Bitmap bmp = new Bitmap(imagefile);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                strbaser64 = Convert.ToBase64String(arr);
            }
            catch (Exception)
            {
                throw new Exception("Something wrong during convert!");
            }
            return strbaser64;
        }

        /// <summary>
        /// 解析图片
        /// </summary>
        /// <param name="imagefile">图片</param>
        /// <returns>流</returns>
        public static string GetBase64FromImage(Bitmap bit)
        {
            string strbaser64 = "";
            try
            {
                Bitmap bmp = new Bitmap(bit);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                strbaser64 = Convert.ToBase64String(arr);
            }
            catch (Exception)
            {
                throw new Exception("Something wrong during convert!");
            }
            return strbaser64;
        }

        /// <summary>
        /// 将Base64转为string
        /// </summary>
        /// <param name="base64">base64串码</param>
        /// <returns>字符串</returns>
        public static string Base64StringToString(string base64)
        {
            if (base64 != "")
            {
                char[] charBuffer = base64.ToCharArray();
                byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
                string returnstr = Encoding.UTF8.GetString(bytes);
                return returnstr;
            }
            else
            {
                return "";
            }
        }


        /// <summary>
        /// 下载服务器文件至客户端
        /// </summary>
        /// <param name="URL">被下载的文件地址，绝对路径</param>
        /// <param name="Dir">另存放的目录</param>
        public static void Download(string URL, string Dir)
        {
            WebClient client = new WebClient();
            string fileName = URL.Substring(URL.LastIndexOf("/") + 1);  //被下载的文件名

            string Path = Dir + fileName;   //另存为的绝对路径＋文件名
            try
            {
                WebRequest myre = WebRequest.Create(URL);
                client.DownloadFile(URL, Path);
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(fs);
                byte[] mbyte = r.ReadBytes((int)fs.Length);

                FileStream fstr = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);

                fstr.Write(mbyte, 0, (int)fs.Length);
                fstr.Close();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Error"); 
            }

        }

        /// <summary>
        /// 结束进程
        /// </summary>
        /// <param name="processName">进程名称</param>
        public static void KillProcess(string processName)
        {
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();
            //得到所有打开的进程   
            try
            {
                foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessesByName(processName))
                {
                    if (!thisproc.CloseMainWindow())
                        thisproc.Kill();                //找到程序进程,kill之。
                }
            }
            catch (Exception Exc)
            {
                MessageBox.Show(Exc.Message);
            }
        }


        /// <summary>
        /// 启动进程
        /// </summary>
        /// <param name="processName">路径+进程名称</param>
        public static void StartProcess(string processName)
        {
            if (System.IO.File.Exists(Application.StartupPath + "\\" + processName))
                System.Diagnostics.Process.Start(Application.StartupPath + "\\" + processName);
            else
                BaseClass.Download("http://download.myline.cc/download/Update.Zhuoying.exe", Application.StartupPath + "\\");

            if (!System.IO.File.Exists(Application.StartupPath + "\\Newtonsoft.Json.dll"))
                BaseClass.Download("http://download.myline.cc/download/Newtonsoft.Json.dll", Application.StartupPath + "\\");
        }

    }
}
